//
//  UIViewController+TYRotation.m
//  TYUIKit
//
//  Created by TuyaInc on 2019/12/12.
//

#import "UIViewController+TYRotation.h"

#import "NSObject+TYUIKitSwizzler.h"
#import <objc/runtime.h>
#import <TYUIKit/TYUIKit.h>

#define kTYDeviceIsRotatingKey ((__bridge const void * _Nonnull)@"kTYDeviceIsRotatingKey")

@implementation UIViewController (TYRotation)

//+ (void)load {
//    [self ty_uikit_swizzleSEL:@selector(viewWillAppear:) withSEL:@selector(_tyswiz_rotate_viewWillAppear:)];
//}
//
//- (void)_tyswiz_rotate_viewWillAppear:(BOOL)animated {
//    [self _tyswiz_rotate_viewWillAppear:animated];
//    [self ty_rotateWindowIfNeed];
//}
- (void)ty_rotateWindowIfNeed {
    UIInterfaceOrientation windowOri = [UIApplication sharedApplication].statusBarOrientation;
    
    if ([UIApplication sharedApplication].keyWindow.rootViewController == nil // rootVC还没加载出来
        || windowOri == UIInterfaceOrientationUnknown // 未知方向
        || ([self respondsToSelector:@selector(shouldAutorotate)] && ![self shouldAutorotate]) // 明确禁止自转
        || ![[UIDevice currentDevice] respondsToSelector:@selector(setOrientation:)] // 无此方法
        ) {
        return;
    }

    UIInterfaceOrientation targetOri = (int)[self ty_preferredOrientationForWindowRotation];
    if (targetOri == UIInterfaceOrientationUnknown || targetOri == windowOri) {
        return;
    }
    // pad 只支持 left 方向的横屏，继续往下走会崩溃
    if (TY_IsPad()) {
        return;
    }
    if (@available(iOS 16.0, *)) {
        @try {
              // 由于目前打包机上的xcode版本并未全面使用xcode14，需使用反射的方式调用新API
            SEL need_sel_method = NSSelectorFromString(@"setNeedsUpdateOfSupportedInterfaceOrientations");
            if ([self respondsToSelector:need_sel_method]) {
                (((void (*)(id, SEL))[self methodForSelector:need_sel_method])(self, need_sel_method));
            }
            NSArray *array = [[[UIApplication sharedApplication] connectedScenes] allObjects];
            UIWindowScene *ws = (UIWindowScene *)array[0];
            Class GeometryPreferences = NSClassFromString(@"UIWindowSceneGeometryPreferencesIOS");
            id geometryPreferences = [[GeometryPreferences alloc]init];
            [geometryPreferences setValue:@([self supportedInterfaceOrientations]) forKey:@"interfaceOrientations"];
            SEL sel_method = NSSelectorFromString(@"requestGeometryUpdateWithPreferences:errorHandler:");
            void (^ErrorBlock)(NSError *err) = ^(NSError *err){
                //业务代码
            };
            if ([ws respondsToSelector:sel_method]) {
                (((void (*)(id, SEL,id,id))[ws methodForSelector:sel_method])(ws, sel_method,geometryPreferences,ErrorBlock));
            }
        } @catch (NSException *exception) {
            //异常处理
        } @finally {
            //异常处理
        }
    } else {
        SEL selector = NSSelectorFromString(@"setOrientation:");
        NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[UIDevice instanceMethodSignatureForSelector:selector]];
        [invocation setSelector:selector];
        [invocation setTarget:[UIDevice currentDevice]];
        int ori = (int)targetOri;
        [invocation setArgument:&ori atIndex:2];
        [invocation invoke];
    }
}

//- (void)ty_rotateWindowIfNeed {
//    UIInterfaceOrientation windowOri = [UIApplication sharedApplication].statusBarOrientation;
//
//    if ([UIApplication sharedApplication].keyWindow.rootViewController == nil // rootVC还没加载出来
//        || windowOri == UIInterfaceOrientationUnknown // 未知方向
//        || ([self respondsToSelector:@selector(shouldAutorotate)] && ![self shouldAutorotate]) // 明确禁止自转
//        || ![[UIDevice currentDevice] respondsToSelector:@selector(setOrientation:)] // 无此方法
//        ) {
//        return;
//    }
//
//    UIInterfaceOrientation targetOri = (int)[self ty_preferredOrientationForWindowRotation];
//    if (targetOri == UIInterfaceOrientationUnknown || targetOri == windowOri) {
//        return;
//    }
//
//    SEL selector = NSSelectorFromString(@"setOrientation:");
//    NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[UIDevice instanceMethodSignatureForSelector:selector]];
//    [invocation setSelector:selector];
//    [invocation setTarget:[UIDevice currentDevice]];
//    int ori = (int)targetOri;
//    [invocation setArgument:&ori atIndex:2];
//    [invocation invoke];
//}

- (UIInterfaceOrientation)ty_preferredOrientationForWindowRotation {
    UIInterfaceOrientationMask oriMask = self.supportedInterfaceOrientations;
    if (oriMask & UIInterfaceOrientationMaskPortrait) {
        return UIInterfaceOrientationPortrait;
    } else if (oriMask & UIInterfaceOrientationMaskLandscapeLeft) {
        return UIInterfaceOrientationLandscapeLeft;
    } else if (oriMask & UIInterfaceOrientationMaskLandscapeRight) {
        return UIInterfaceOrientationLandscapeRight;
    } else if (oriMask & UIInterfaceOrientationMaskPortraitUpsideDown) {
        return UIInterfaceOrientationPortraitUpsideDown;
    } else {
        return UIInterfaceOrientationUnknown;
    }
}

@end
